<template>
  <SdyHeader title="啥都有">
    <template #left>
      <van-icon 
      class="cate-icon"
       name="aim" 

        />
               <!-- @click='addBannerImg' -->
    </template>
    <template #title>
      <van-search @focus="inSearchHandler" shape="round" background="#c72418" placeholder="请输入搜索关键词" />
    </template>
    <template #right>
      <!-- <span v-if='inLogin'>{{username}}</span> -->
          <van-image
           v-if='inLogin' 
           @click='$router.push("/self")'
            round
            width="2.5rem"
            height="2.5rem"
            src="https://img1.baidu.com/it/u=1159918860,1753333606&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=457"
          />
      <span v-else @click='loginHandler'>登录</span>
    </template>
  </SdyHeader>

  <!-- 轮播图 -->
  <SdyHomeBanner />

  <!-- 分类导航列表组件 -->
  <SdyHomeNavList />

  <!-- 首页秒杀热门 -->
  <SdyHomeHot />

  <!-- 商品列表 -->
   <SdyHomeGoodsList></SdyHomeGoodsList>
</template>

<script setup lang="ts">
// 导入组件使用
import SdyHomeBanner from './components/SdyHomeBanner.vue'
import SdyHomeNavList from './components/SdyHomeNavList.vue'
import SdyHomeHot from './components/SdyHomeHot.vue'
import SdyHomeGoodsList from './components/SdyHomeGoodsList.vue'
import { useRouter, type Router } from 'vue-router'
import {ref,onMounted} from 'vue'
import {getUserInfoApi} from '@/api/users'
//导入插入轮播图接口
// import {addBannerImgApi} from '@/api/banner'

// 拿到编程式导航的路由控制器
const $router: Router = useRouter()

// 点击搜索框进入到 search 路由
const inSearchHandler = () => {
  // console.log($router)
  // 进行路由跳转
  $router.push('/search')
}
const loginHandler = ()=>{
  console.log($router)
  $router.push('/login')
}

//表示是否登录
const inLogin = ref<boolean>(false)
//准备一个变量表示用户名
const avatar = ref<string>('')
//登录按钮显示什么
//1.验证token
const testToken = async () => {
  // 从localStorage内拿到token验证
  //如果没有说明没有登录过
  const token = window.localStorage.getItem('token')
  const user_id = window.localStorage.getItem('user_id')

  if(!token || !user_id){
    inLogin.value = false
  }
  //如果有说明登录过，但是可能登录已经过期
  // 根据id和token请求信息
  const res = await getUserInfoApi(user_id as string)
  // console.log(res)
  //判断结果 10019
  if(((res as unknown) as {code:string}).code === '10019'){
    inLogin.value = false
    return
  }

  //表示登录过
  inLogin.value = true
  avatar.value = res.data[0].username
}

//addBannerImg插入轮播图图片
// const addBannerImg = async () =>{
//   const res = await addBannerImgapi()
//   console.log(res)
//没token。不写了qwq
// }

onMounted(()=>{
  testToken()
})
</script>

<style scoped lang="scss">
@import '@/styles/variable.scss';
.cate-icon {
  font-size: 24px;
  color: orange;
}
</style>
